package com.ujiuye.severlet;

import com.ujiuye.Service.ManagerService;
import com.ujiuye.Service.impl.ManagerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/managerServlet")
public class ManagerServlet extends BaseServlet {
    ManagerService ms = new ManagerServiceImpl();

    protected void login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean res = ms.login(username, password);
        if (!res) {
            response.sendRedirect("register.html");
        } else {
            String rem = request.getParameter("rem");
            //如果rem的值为ok，则代表用户勾选了记住密码
            if ("ok".equals(rem)) {
                //记住密码
                Cookie nameCookie = new Cookie("username",username);
                nameCookie.setMaxAge(60*60*24*15);
                response.addCookie(nameCookie);
                Cookie pwdCookie = new Cookie("password",password);
                pwdCookie.setMaxAge(60*60*24*15);
                response.addCookie(pwdCookie);
            } else {
                //取消之前记住的密码
                //利用Cookie覆盖的特性，将之前同名的Cookie覆盖删除掉
                Cookie nameCookie = new Cookie("username",null);
                nameCookie.setMaxAge(0);
                response.addCookie(nameCookie);
                Cookie pwdCookie = new Cookie("password",null);
                pwdCookie.setMaxAge(0);
                response.addCookie(pwdCookie);
            }
            response.sendRedirect("index.jsp");
        }
    }

    protected void register(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean res = ms.register(username, password);
        PrintWriter out = response.getWriter();
        if (!res) {
            out.print("<script>alert('注册失败')</script>");
            out.close();
        } else {
            response.sendRedirect("login.jsp");
        }
    }
}
